package com.gitbl.webchat.web.control;

import com.gitbl.webchat.web.webmessage.WebError;
import com.gitbl.webchat.web.webmessage.WebUser;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class DefaultInterceptor extends BaseController implements HandlerInterceptor {
    Set<String> urlsnotneedlogin;
    Pattern pathPattern;
    public DefaultInterceptor(){
        urlsnotneedlogin = new HashSet<>();
        //注册登录相关
        urlsnotneedlogin.add("/user/login");
        urlsnotneedlogin.add("/user/signup");
        urlsnotneedlogin.add("/user/exist");
        //错误
        urlsnotneedlogin.add("/error");
        //首页
        urlsnotneedlogin.add("/");

        //静态页面
        pathPattern = Pattern.compile("^.+\\.(css|html|js|png|jep|gif)$");


    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url = request.getRequestURI();
        if(urlsnotneedlogin.contains(url)){
            return true;
        }
        Matcher matcher = pathPattern.matcher(url);
        if(matcher.matches()){
            return true;
        }
        String token="";
        if(token.isEmpty())
            token = request.getParameter("token");
        if(token==null||token.trim().isEmpty()){
            response.getWriter().write(WebError.STR_PARAMSERROR);
            return false;
        }

        WebUser u = getUserByToken(token);
        if(u==null){
            response.getWriter().write(WebError.STR_NOTLOGIN);
            return false;
        }

        request.setAttribute( A_USER,u);

        return true;
    }

    /**
     * 在控制器的方法调用之后调用，但是抛出异常之后不会进入这个方法
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 不管是正常调用还是抛出异常都会被调用
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
